<?php

namespace app\index\controller;

use app\common\model\System;
use think\Controller;
use think\Cookie;
use think\Request;

class Index extends Controller
{
    public function _initialize()
    {
        if (!Cookie::has('uid')) {
            $this->redirect('user/index');
        }
//        $this->assign('sysConfig', $sysConfig);
    }

    public function index()
    {
//        2018年7月21日11:26:46 修改
        $list = model('System')->head_img();
        $sysConfig = model('System')->sysConfig();
        $zaoqi = $this->touch_goal_early();
        $lianxu = $this->most_touch_goal();
//        model('Projectitem')->unsignedMoney();
//       $res = $this->most_touch_goal();
        $Project = model('Project');
        $projectitemObj = model('Projectitem');
        $projectitem = $projectitemObj->getItem();//获取今日打卡项
        //print_r($projectitem);exit;
        $isExist = $Project->projectIsExists();//判断当前是否有参加
        $projectPrice = $Project->getProjectPrice();//获取当前项目金额
        $be_left_time = '';//剩余时间
        /*$beginshow=$projectitem['create_time']+$projectitem['sign_time'];
        $endshow=$projectitem['create_time']+$projectitem['sign_time']+60*60;//增加3600秒至7：30*/
        $beginshow = $projectitem['signbegin_time'];
        $endshow = $projectitem['signbegin_time'] + 60 * 60;

        if ($projectPrice) {
            $be_left_time = $projectitem['create_time'] + $projectitem['sign_time'] - time();
        }

        return $this->fetch('', [
            'isExist' => $isExist,
            'projectPrice' => $projectPrice, //当前项目投入金额
            'sysConfig' => $sysConfig,
//            2018年7月21日11:27:01 修改
            'list' => $list,     //循环的头像列表
            'beleft_time' => $be_left_time,//倒计时秒数
            'beginshow' => $beginshow,//显示倒计时开始时间，减去的为测试时长
            'endshow' => $endshow,//显示倒计时结束时间
            'zaoqi' =>$zaoqi,
            'lianxu' => $lianxu
        ]);
    }

    //个人中心
    public function center(Request $request)
    {
        $res = model('User')->getUinfo();
        if(!$res){
            return $this->result('',1,'该用户不存在');
        }
        if($request->isAjax()){
            $img = input('img');
            $result = model('User')->where('id',$res['id'])->setField('portrait',$img);
            if($result){
                return $this->result('',0,'头像上传成功');
            }else{
                return $this->result('',1,'头像上传失败,请重新上传');
            }
        }
        $team = model('UserprofitLogs')->getteamprofit();
        $config = model('System')->sysConfig();
        $this->assign('team',$team);
        $this->assign('config',$config);
        $this->assign('userinfo',$res);
        return $this->fetch();
    }

    /**
     * 我的团队
     */
    public function myteam(){
       $team = model('User')->myteammates();
       $tmoney = 0;
//       计算团队总参与资金
       foreach ($team as $k=>$v){
           $tmoney += isset($v['join_money'])?$v['join_money']:0;
       }
       $this->assign('tmoney',$tmoney);
       $this->assign('team',$team);
        return $this->fetch();
    }


    /**
     * 实时动态
     * @param Request $request
     */
    public function real(Request $request){
//        $user = model('project');
        $where = [
            'p.status' => 0
        ];
       $res =  db('project')->alias('p')->where($where)->order('add_time','desc')->join('User','p.uid = User.id')->limit(9)->select();
       return $this->result($res,1,'获取成功');
    }

    public function rili(){
        $uinfo = model('User')->getUinfo();
        $sys=model('System')->sysConfig();
        $this->assign('sys',$sys);
        // print_r(cookie('uid'));exit;
        return $this->fetch('', ['uinfo' => $uinfo]);
    }

    public function read()
    {
        return $this->fetch();
    }

    /**
     * 提现
     * @return mixed
     */
    public function money()
    {
        $userid = cookie('uid');
        $cashlog = db('cash')->where('uid',$userid)->order('create_time',"desc")->select();
        $user = model('user');
        $userinfo = $user->getUinfo();
        $this->assign('cashlog',$cashlog);
        $this->assign('userinfo',$userinfo);
        return $this->fetch();
    }

    //我的海报
    public function poster()
    {
        $userid = cookie('uid');
//        注册邀请码
//        $code = $this->GetRandStr(6);
        $code = $userid;
        db('user')->where('id',$userid)->setField('invcode',$code);
        $res = db('user')->find($userid);
        /*if($res){
            if(!$res['invcode']){
                $res['invcode'] = $code;
            }
        }*/
        $this->assign('code',$res['invcode']);
        return $this->fetch();
    }

    /*优惠券页面*/
    public function coupon()
    {
        $discount = model('Discounts');
        $list = $discount->getDiscounts();
        $this->assign('list', $list);
        return $this->fetch();
    }
    /*我的优惠券页面*/
    public function my_coupon()
    {
       // print_r(cookie('uid'));exit;
        $discount = model('UserDiscounts');
        $list = $discount->where(['uid'=>cookie('uid'),'status'=>0])->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    //领取优惠券
    public function get_coupon()
    {
        if (request()->isPost()) {
            $id=input('post.id');
            if (empty($id)) {
                return $this->result('', 1, '参数错误');
            }
            $where = [
                'id' => $id,
                'surplus' => ['neq', 0],
                'status' => 0
            ];
            $res = model('Discounts')->where($where)->find();
            $userDis=model('UserDiscounts');
           // print_r($userDis);exit;
            if ($res){
                if ($res['surplus'] == 0){
                    return $this->result('', 1, '优惠券已被领完 ');
                }
                if ($res['status'] == 1){
                    return $this->result('', 1, '优惠券已被领完 ');
                }
                if(model('UserDiscounts')->where(['uid'=>cookie('uid'),'dis_id'=>$id])->find()){
                    return $this->result('', 1, '不能重复领取');
                }

               $dec=model('Discounts')->where(['id'=>$id])->setDec('surplus');
                if($dec){
                    $add_data=[
                        'dis_id'=>$id,
                        'uid'=>cookie('uid'),
                        'money'=>$res['money'],
                        'create_time'=>time()

                    ];
                    $add_res=$userDis->insert($add_data);
                    if($add_res){
                        return $this->result('', 0, '领取成功');
                    }else{
                        return $this->result('', 0, '领取失败');
                    }
                }else{
                    return $this->result('', 1, '领取失败');
            }

            }else{
                return $this->result('', 1, '领取失败');
            }
        }
    }

    /*打卡详情*/
    public function details()
    {
        $projectItem = model('Projectitem');
        $items = $projectItem->getAllSigned();
        $this->assign('list', $items);
        return $this->fetch();
    }

    //通过当日时间获取打卡获取金额
    public function getToDayMoney()
    {
        $date = strtotime(input('date'));
        $this->result($date, 0);
    }

    //获取打卡记录
    public function RefactorItem()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $year = $data['year'];
            $month = $data['month'];
            $list = model('Projectitem')->getToMoney($year, $month);
            $arr = [];
            if ($list) {
                foreach ($list as $k => $v) {
                    $days = date('d', $v['signbegin_time']);
                    $arr[$days] = ['money' => $v['money'], 'status' => $v['status']];
                }
            }
            //     print_r($arr);exit;
            return $this->result($arr);
        }
    }

    /**
     * 每天早起之星
     */
    public function touch_goal_early(){
        $today = strtotime(date('Y-m-d').'6:30');
        $where = [
            'a.status' => 1,
            'create_time' => ['gt',$today]
        ];
       $data = db('projectitem')->alias('a')->where($where)->join('User','a.uid = User.id')->order('create_time','asc')->find();
       return $data;
    }

    /**
     * 毅力之星
     */
    public function most_touch_goal(){

       $data = db('project')->alias('p')->join('User','p.uid = User.id')->order(['signed_count'=>'desc'])->find();
       return $data;
    }

    /**
     * 客服
     */
    public function service(){
       $service = db('setting')->where('key','service')->find();
       $service = json_decode($service['value'],true);
       $this->assign('service',$service);
       return $this->fetch();
    }

    //获取随机数
    private function GetRandStr($length = 4)
    {
        return str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
    }


}
